package com.sykj.springboot.controller.login;

import com.sykj.springboot.common.contants.MapCatchs;
import com.sykj.springboot.common.entity.JsonResult;
import com.sykj.springboot.common.utils.RedisUtils;
import com.sykj.springboot.entity.SysUser;
import com.sykj.springboot.entity.User;
import com.sykj.springboot.service.SysUserService;
import com.sykj.springboot.service.UserService;
import com.sykj.springboot.syslog.CustomLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("login")
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    SysUserService sysUserService;

    @CustomLog()
    @RequestMapping("login")
    public JsonResult login(HttpServletRequest request, HttpServletResponse response,String userid, String password){
        JsonResult result = new JsonResult();
        if (StringUtils.isEmpty(userid)){
            result.setMsg("用户为空");
            result.setStatus(JsonResult.TIME_OUT);
        }
        try {
            SysUser byId = sysUserService.getById(userid);
            if (byId!=null){
                if (!byId.getPassword().equals(password)){
                    result.setMsg("密码错误");
                    result.setStatus(JsonResult.TIME_OUT);
                }else{
                    Map<String,Object> memberMap = new HashMap<>();
                    String token_uuid = UUID.randomUUID().toString();
                    RedisUtils.addToken(token_uuid,byId);
                    memberMap.put("token",token_uuid);
                    memberMap.put("userInfo",byId);
                    result.setData(memberMap);
                    result.setStatus(JsonResult.SUCCESS);
                }
            }else{
                result.setMsg("用户不存在");
                result.setStatus(JsonResult.TIME_OUT);
            }
        } catch (Exception e) {
            result.setMsg("数据库链接异常");
            result.setStatus(JsonResult.ERROR);
        }
        return result;
    }
}
